package org.example.practice.controller;

import jakarta.servlet.http.HttpServletResponse;
import org.example.practice.entity.Person;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;

@RequestMapping("/return")
@Controller
public class ReturnController {
    @RequestMapping("/returnPage")
    @ResponseBody
    public String returnString() {
        return "Hello World";
    }
    @RequestMapping("/html")
    @ResponseBody
    public String returnJson() {
        return "<h1>returnHTML</h1>";
        //会显示为 html页面
    }
    @RequestMapping("/returnPage1")
    //返回/index.html页面
    public String returnPage(){
        return "/index.html";
    }
    @RequestMapping("/returnData")
    @ResponseBody
    //返回/index.html
    public String returnData() {
        return "/index.html";
    }
    @ResponseBody
    @RequestMapping("/returnJSON")
    //引用了@ResponseBody注解并且项目中引入了 JSON 转换器
    public Person returnJSON(){
        Person person = new Person();
        person.setName("zhangsan");
        person.setAge(12);
        person.setPassword("123456");
        return person;
    }
    @ResponseBody
    @RequestMapping("/setStatus")
    public String setStatus(HttpServletResponse response){
        response.setStatus(502);
        return "设置状态码为502";
    }
    @ResponseBody
    @RequestMapping("/setHeader")
    public String setHeader(HttpServletResponse response){
        response.setHeader("My-Header","MyHeader");
        return "设置响应头My-Header:MyHeader";
    }
    @ResponseBody
    @RequestMapping("/setContentType")
    public void setContentType(HttpServletResponse response) throws IOException {
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        response.getOutputStream().write("设置响应头Content-Type:text/html;charset=utf-8".getBytes());
    }
    @ResponseBody
    @RequestMapping(value = "/setContentType2", produces = "text/plain")
    public String setContentType2(){
        //返回<h1>returnHTML</h1>
        return "<h1>returnHTML</h1>";
    }
    @ResponseBody
    @RequestMapping(value = "/setContentType3", produces = "application/json")
    public String setContentType3(){
        //相应内容为produces = "application/json
        //返回{"OK": 1}json
        return "{\"OK\": 1}";
    }
}
